<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert show-icon :closable="false" title="警告:只允许为第三级分类设置相关参数" type="warning"></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!--动态参数-->
          <el-table :data="manyTableData" border stripe>
            <!--展开行-->
            <el-table-column type="expand">
              <!-- 标签栏 -->
              <template slot-scope="scope">
                <el-tag
                  class="valsTag"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index" @close="deleteClose(index,scope.row)"
                >{{ item }}</el-tag>
                <!-- 文本框的点击与隐藏 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="success"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!--静态参数-->
          <el-table :data="onlyTableData" border stripe>
            <!--展开行-->
            <el-table-column type="expand">
              <!-- 标签栏 -->
              <template slot-scope="scope">
                <el-tag
                  class="valsTag"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index" @close="deleteClose(index,scope.row)"
                >{{ item }}</el-tag>
                <!-- 文本框的点击与隐藏 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="success"
                  icon="el-icon-edit"
                  @click="showEditDialog((scope.row.attr_id))"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeData(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数的对话框-->
    <el-dialog
      :title="'添加'+dialogText"
      @close="addFormClose"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form ref="addFormRef" :model="addForm" label-width="100px" :rules="addformRules">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑对话框-->
    <el-dialog
      :title="'添加'+dialogText"
      @close="editFormClose"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editformRules">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      //   级联选择器双向绑定的数组
      selectKeys: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // tab标签切换默认选项
      activeName: "many",
      // 动态参数
      manyTableData: [],
      // 静态参数
      onlyTableData: [],
      addDialogVisible: false,
      // 表单验证数据
      addForm: {
        attr_name: ""
      },
      // 编辑数据
      editForm: {},
      // 编辑显示与隐藏
      editDialogVisible: false,
      // 添加验证规则
      addformRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      // 编辑验证规则
      editformRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      
    };
  },
  created() {
    this.getCateList();
  },
  computed: {
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中三级分类的id
    isComputedId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2];
      }
      return null;
    },
    dialogText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态参数";
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data;
      console.log(this.cateList);
    },
    // 级联选择框中发生改变时，会触发这个函数
    handleChange() {
      this.getParamsData();
    },
    handleClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData() {
      // 证明不是三级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[]
        return;
      }
      // 证明选中的是三级分类
      console.log(this.selectKeys);
      //  根据所选分类的参数，获取对应得id
      const { data: res } = await this.$http.get(
        `categories/${this.isComputedId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      // attr_vals将字符串进行forEach并转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 为每一个tag标签的显示与隐藏
        item.inputVisible=false
        item.inputValue=''
      });
      console.log(res.data);
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      console.log(res.data);
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    addFormClose() {
      this.$refs.addFormRef.resetFields();
    },
    addClick() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.isComputedId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 编辑操作
    editFormClose() {
      this.$refs.editFormRef.resetFields();
    },
    editClick() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error("验证失败");
        const { data: res } = await this.$http.put(
          `categories/${this.isComputedId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("编辑失败");
        }
        this.$message.success("编辑成功");
        this.editDialogVisible = false;
        this.getParamsData();
      });
    },
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.isComputedId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 删除
    async removeData(attr_id) {
      const confirmRelust = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // 删除的逻辑
      if (confirmRelust !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.isComputedId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getParamsData();
    },
    // tab键盘按下
   async handleInputConfirm(row) {
      if(row.inputValue.trim().length===0){
        row.inputValue=''
        row.inputVisible=false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
       row.inputValue=''
        row.inputVisible=false
        this.saveAttrVals(row)
    },
    // 将对attr_vals 保存到数据库
    async saveAttrVals(row){
      const {data:res}=await this.$http.put(`categories/${this.isComputedId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        })
        if(res.meta.status!==200){
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
      console.log("ok");
    },
    // 点击按钮
    showInput(row){
      row.inputVisible=true
      // 让文本框自动获取焦点 $nextTick是页面渲染之后执行此函数
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        }); 
    },
    // 删除便签操作
    deleteClose(index,row){
      row.attr_vals.splice(index,1)
      this.saveAttrVals(row)
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.valsTag {
  margin: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>